<?php
declare (strict_types = 1);
/**
 * 编单模型
 */
namespace app\common\model;
use app\common\facade\model\PlayListModel;   // 播出串联单表模型
use app\common\facade\model\AdvseqModel;     // 广告时段模型
use app\common\facade\model\AdvPgmListModel; // 广告节目单模型
use app\common\facade\model\AdvPgmListDetailModel; // 广告节目单明细表模型
use app\common\facade\model\PgmGroupDetailModel; // 节目组明细模型
use app\common\facade\model\MaterialModel; // 素材模型
use app\common\facade\model\PlayTimeModel; // 播出时间计算模型


class PlayListDetail extends BaseModel
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 't_play_list_detail';

    public function detailLists($where = [], $ordername='seq', $order= 'asc')
    {
        $field = '*';

        $list = self::field($field)->where($where)->order([$ordername => $order])->select()->toArray();
        // var_dump(self::getLastSql());

        $nres = PlayListModel::where([['pgmlist_id', '=', $where[0][2]]])->find()->toArray(); // 编单表模型主键

        // 根据当前频道,和编单日期 获取当前日期时段列表。
        $adb_seq_list = AdvseqModel::advseqalive(['channel_id' => $nres['channel_id'], 'play_date' => $nres['pl_date']]);

        // 广告节目单模型主键
        $pl_id = AdvPgmListModel::where([['play_date', '=', $nres['pl_date']], ['channel_id', '=', $nres['channel_id']]])->value('pl_id');

        foreach($list as $k => $v) {
            if($v['grp_flag'] == 1) {
                // 统计广告单时段下节目总时长。
                $pgm_len = AdvPgmListDetailModel::where([['advseg_id', '=', $v['pgm_id']], ['pl_id', '=', $pl_id]])->sum("pgm_len")?:0;
                $list[$k]['pgm_len'] = $v['pgm_len']!= $pgm_len ? $pgm_len : $v['pgm_len'];
                $list[$k]['adv_pl_id'] = $pl_id;
            } else if($v['grp_flag'] == 2) {
              // 统计节目组时长
              $pgm_len = PgmGroupDetailModel::pgmgrp_len([['pgmgrp_id', '=', $v['pgm_id']]]);
              $list[$k]['pgm_len'] = $v['pgm_len']!= $pgm_len ? $pgm_len : $v['pgm_len'];
            } else {
               if(empty($v['mat_id'])) {
                $pgm_len = $v['pgm_len'];
               } else {
                $pgm_len = MaterialModel::where([['mat_id', '=', $v['mat_id']]])->value('file_len');
               }
            }

            $list[$k]['true_pgm_len'] = $pgm_len; // 节目真实长度

            
            /*  
            // 播出时间统一交由前端计算处理
            
            if(in_array($v['play_mode'], [1, 2])) { // 顺序，触发节目
              $list[$k]['s_time_play'] = $v['s_time'];
            } else {
              $list[$k]['s_time_play'] = PlayTimeModel::computedPlayTime($list, $k); // 插播节目播放时间计算
            } */
        }

        return [
          'list' => $list,
          'start_time' => empty($adb_seq_list['list'])? 0 : $adb_seq_list['list'][0]['s_time_code'] // 首播时间
        ];
    }
}
